package io.gitee.xjt2016.modules.security;

import io.gitee.xjt2016.modules.domain.sys.User;
import io.gitee.xjt2016.modules.service.sys.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Slf4j
public class LoginController {
    public static final String loginUrl = "/login";
    public static final String indexUrl = "/index";

    @Resource
    UserService userService;

    @GetMapping("/login")
    public String loginGet() {
        return loginUrl;
    }

    @PostMapping("/login")
    public String loginPost(User user,
                            HttpServletRequest request,
                            HttpServletResponse response,
                            RedirectAttributes attributes) {
        String error = "";
        String url = loginUrl;
        try {
            boolean result = userService.login(user.getUsername(), user.getPassword(), response);
            if (result) {
                url = indexUrl;
            }
        } catch (Throwable throwable) {
            error = throwable.getMessage();
        }
        if (StringUtils.isNotBlank(error)) {
            attributes.addFlashAttribute("error", error);
        }
        return "redirect:" + url;
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        //用户认证信息
        userService.logout(request, response);
        return "redirect:" + loginUrl;
    }
}
